let router = require('koa-router')()
let Camera = require('../model/camera')
let liveStreamService = require('../services/live-stream')

router.prefix('/camera')

router.get('/', async (ctx, next) => {
    await ctx.render('camera')
})

router.get('/list', async (ctx, next) => {
    const cameras = await Camera.findAll({
        attributes: {
            exclude: ['password']
        }
    })
    ctx.body = cameras
})

router.post('/', async (ctx, next) => {
    let {auto} = ctx.request.body
    let camera = Camera.build(ctx.request.body)
    if (auto == 20) camera.url = getUrl(camera)
    let result = await camera.save()
    ctx.body = result
})


router.delete('/:id', async (ctx, next) => {
    let id = ctx.params.id
    await Camera.destroy({
        where: {
            id
        }
    })
    ctx.body = ""
})

/*修改逻辑*/
router.put('/', async (ctx, next) => {

})


router.post('/connect/:id', async (ctx, next) => {
    const camera = await Camera.findByPk(ctx.params.id)
    if(camera){
        liveStreamService.connect(camera)
    }
})


function getUrl(camera) {
    let {ip, userName, password, channel, port} = camera
    return `rtsp://${userName}:${password}@${ip}:${port}/h264`
}

module.exports = router
